package cn.lyjuan.payment.third.base.pay.chl.impl.ali.util;

import cn.lyjuan.payment.third.base.pay.chl.impl.ali.bean.AliChlCnf;
import cn.lyjuan.payment.third.base.pay.cst.PayConst;
import cn.lyjuan.payment.third.base.pay.enums.SimpleStatusEnum;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

// todo 修改
@Slf4j
public class AlipayQuery {
    //public static <T> T  query(String localNo, AliChlCnf cnf, boolean isDebug) {
//        return null;
//    }
    public static AlipayTradeQueryResponse query(String localNo, AliChlCnf cnf, boolean isDebug) {
        DefaultAlipayClient alipayClient;
        try {
            alipayClient = AlipaySubmit.makeCertAlipayClient(cnf.getCertPath(), cnf, isDebug);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        Map<String, String> map = new HashMap<>();
        map.put("out_trade_no", localNo);
        request.setBizContent(JSONObject.toJSONString(map));
        try {
            AlipayTradeQueryResponse response = alipayClient.certificateExecute(request);
            //这里和普通的接口调用不同，使用的是sdkExecute
            return response;
        } catch (Exception e) {
            throw new RuntimeException("query tran failed", e);
        }
    }


    public static String parseMsg(Object response) {
        return "";
    }

    /**
     * 解析描述信息
     *
     * @param response
     * @return
     */
    public static String parseMsg(AlipayTradeQueryResponse response) {
        return response.getCode() + "-" + response.getMsg() + "-" + response.getSubCode() + "-" + response.getSubMsg();
    }
//    public static SimpleStatusEnum parseStatus(Object response) {
    //return null;
    //}

    /**
     * 解析交易状态
     *
     * @param response
     * @return
     */
    public static SimpleStatusEnum parseStatus(AlipayTradeQueryResponse response) {
        if ("TRADE_SUCCESS".equalsIgnoreCase(response.getTradeStatus()))
            return SimpleStatusEnum.SUCC;

        return SimpleStatusEnum.UNKNOWN;
    }
}
